/*
 * Copyright (C) ${year} Jeffrey Palm.
 *
 * This code is part of the Floto Project (http://jeffpalm.com/floto/).
 * Please consult the LICENSE included in the distribution.
 */
package com.jeffpalm.floto.isight.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;

/**
 * General configuration for this machine or device.
 */
public abstract class Config {

  private final String name;
  private final Log log;
  private final ErrorHandler errorHandler;
  private final Properties props = new Properties();

  /**
   * @param alarmac
   */
  protected Config(String name, Log log, ErrorHandler errorHandler) {
    this.name = name;
    this.log = log;
    this.errorHandler = errorHandler;
  }
  
  public final void set(String key, String val) {
    props.setProperty(key, val);
  }

  public final String get(String key, String defaultValue) {
    String s = props.getProperty(key);
    if (s == null) {
      set(key, defaultValue);
      return defaultValue;
    } else {
      return s;
    }

  }

  public final String get(String key) {
    return get(key, "");
  }

  public final void startUp() {
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
      public void run() {
        saveOptions();
      }
    }));
    loadOptions();
  }
  
  private String name() {
    return name;
  }

  private File optionsFile() {
    return new File(getOutDir(), "." + name());
  }

  public final void loadOptions() {
    try {
      File f = optionsFile();
      if (f.exists()) {
        InputStream in = new FileInputStream(f);
        props.load(in);
        in.close();
      }
    } catch (Exception e) {
      errorHandler.handle(e);
    }
    log.note(this, "Loaded options: " + props);
  }

  public final void saveOptions() {
    log.note(this, "Saving options: " + props);
    try {
      props.store(new FileOutputStream(optionsFile()), name());
    } catch (Exception e) {
      errorHandler.handle(e);
    }
  }

  final File getOutDir() {
    return new File(System.getProperty("user.home"));
  }
  
}